package com.bricker.laboratorymanagement.business.controller;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bricker.laboratorymanagement.business.entity.SysGroup;
import com.bricker.laboratorymanagement.business.model.GroupSelectModel;
import com.bricker.laboratorymanagement.business.service.SysGroupService;
import com.bricker.laboratorymanagement.business.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/group")
public class SysGroupController {

    @Autowired
    private SysGroupService sysGroupService;
    @Autowired
    private SysUserService sysUserService;
    @GetMapping
    public Page<SysGroup> getSysGroup(HttpServletRequest request, GroupSelectModel groupSelectModel){
        String token=request.getHeader("access_token");
        Long uId= Long.valueOf(JWT.decode(token).getAudience().get(0));
        groupSelectModel.setCurrentUid(uId);
        Page<SysGroup> page =sysGroupService.getSysGroup(groupSelectModel);
        List<SysGroup> list = page.getRecords();
        for (SysGroup sysGroup : list) {
            if(sysGroup.getStatus()==null){
                sysGroup.setStatus("3");
            }
            String userIds=sysGroup.getUserIds();
            if(!StringUtils.isEmpty(userIds)){
                List<String> ids= Arrays.asList(userIds.split(","));
                sysGroup.setCurrentSize(ids.size());
            }
        }
        return page.setRecords(list);
    }

    @PostMapping
    public Map<String,String> saveOrUpdMySysGroup(HttpServletRequest request,@RequestBody List<SysGroup> groupList){
        String token=request.getHeader("access_token");
        Long uId= Long.valueOf(JWT.decode(token).getAudience().get(0));
        return sysGroupService.saveOrUpdMySysGroup(uId,groupList);
    }

    @GetMapping("/getMySysGroup")
    public SysGroup getMySysGroup(HttpServletRequest request){
        String token=request.getHeader("access_token");
        Long uId= Long.valueOf(JWT.decode(token).getAudience().get(0));
        Long groupId=sysUserService.getById(uId).getGroupId();
        SysGroup sysGroup=null;
        if(groupId!=null){
            sysGroup =sysGroupService.getMySysGroup(groupId);
        }
        return  sysGroup;
    }
}
